import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import request from 'umi-request';

const api = (obj: any) => {
  return request
    .get('http://www.pudge.wang:3333/api/students/list', {
      params: obj ? obj : {},
    })
    .then((res) => {
      return res;
    });
};

export interface IndexModelState {
  dataSource: any;
  count: number;
}

export interface IndexModelType {
  namespace: 'city';
  state: IndexModelState;
  effects: {
    loadAsync: Effect;
  };
  reducers: {
    load: Reducer;
    // 启用 immer 之后
    // save: ImmerReducer<IndexModelState>;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  namespace: 'city',

  state: {
    dataSource: [],
    count: 0,
  },

  effects: {
    *loadAsync({ payload }, { call, put }): any {
      const res = yield call(() =>
        api({ page_size: payload.pageSize, current_page: payload.page }),
      );

      const list = res.result.map((item: any) => ({ ...item, key: item._id }));

      yield put({
        type: 'load',
        payload: list,
        count: res.count,
      });
    },
  },
  reducers: {
    load(state, action) {
      return {
        ...state,
        dataSource: action.payload,
        count: action.count,
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/home/city2') {
          dispatch({
            type: 'loadAsync',
            payload: {
              pageSize: 10,
              page: 1,
            },
          });
        }
      });
    },
  },
};

export default IndexModel;
